﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.StorageClient;
using Microsoft.WindowsAzure.ServiceRuntime;
using System.Configuration;
using System.Diagnostics;
using System.Data.Services.Client;
 

namespace PC.AzureMultiApp.Storage
{
    /// <summary>
    /// DataSource to access to Tables
    /// </summary>
    public class ApplicationDataSource
    {
        StorageContext context;

        public ApplicationDataSource()
        {
            CloudStorageAccount.SetConfigurationSettingPublisher((configName, configSetter) =>
            {
                if (RoleEnvironment.IsAvailable)
                    configSetter(RoleEnvironment.GetConfigurationSettingValue(configName));
                else
                    configSetter(ConfigurationManager.AppSettings[configName]);
            });


            var sa = CloudStorageAccount.FromConfigurationSetting("azuremultiappstorage");

            this.context = new StorageContext(sa.TableEndpoint.ToString(), sa.Credentials);

            var ctc = sa.CreateCloudTableClient();

            ctc.CreateTableIfNotExist(GlobalDef.TableName);
        }

        public IEnumerable<AzureApplicationEntity> GetAll()
        {
            var result = from c in this.context.Applications
                            select c;

            var query = result.AsTableServiceQuery<AzureApplicationEntity>();

            var queryResults = query.Execute();

            return queryResults;
        }

        public void Delete(AzureApplicationEntity entity)
        {
            if (entity == null)
                throw new ArgumentNullException("entity");

            this.context.DeleteObject(entity);
            this.context.SaveChanges();
        }

        public void Clear()
        {
            foreach (var item in this.context.Applications)
                this.context.DeleteObject(item);
            this.context.SaveChanges();
        }

        public void Insert(AzureApplicationEntity entity)
        {
            if (entity == null)
                throw new ArgumentNullException("entity");

            this.context.AddObject(GlobalDef.TableName, entity);
            this.context.SaveChanges();
        }

        public void UpdateStatus(string uniqueId, string status)
        {
            var customerToUpdate = this.context.Applications.Where(c => c.UniqueId.Equals(uniqueId, StringComparison.OrdinalIgnoreCase)).FirstOrDefault();

            if (customerToUpdate != null)
            {
                customerToUpdate.Status = status;

                this.context.UpdateObject(customerToUpdate);
                this.context.SaveChanges();
            }
        }

        public void Update(string uniqueId, AzureApplicationEntity entity)
        {
            if (entity == null)
            {
                throw new ArgumentNullException("entity");
            }

            var customerToUpdate = this.context.Applications.Where(c => c.UniqueId.Equals(uniqueId, StringComparison.OrdinalIgnoreCase)).FirstOrDefault();

            if (customerToUpdate != null)
            {
                customerToUpdate.Name = entity.Name;
                customerToUpdate.ApplicationName = entity.ApplicationName;
                customerToUpdate.ApplicationUrl = entity.ApplicationUrl;
                customerToUpdate.BlobUrl = entity.BlobUrl;
                customerToUpdate.Label = entity.Label;
                customerToUpdate.Version = entity.Version;
                customerToUpdate.IsWebDeploy = entity.IsWebDeploy;
                if (!String.IsNullOrEmpty(entity.Status))
                    customerToUpdate.Status = entity.Status;

                this.context.UpdateObject(customerToUpdate);
                this.context.SaveChanges();
            }
        }

    }
}
